package com.movitech.mobile.cz.base.common.aop;

import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * controler 层抛出的异常的统一常规处理
 */
@RestControllerAdvice
public class ControllerExceptionHandleAdvice {
    private final static Logger logger = Logger.getLogger(ControllerExceptionHandleAdvice.class);

    @ExceptionHandler
    public RestReturnResult handler(HttpServletRequest req, HttpServletResponse res, Exception e) {

//        if (res.getStatus() == HttpStatus.BAD_REQUEST.value()) {
//            res.setStatus(HttpStatus.OK.value());
//        }
        logger.error(e);
        if (e instanceof RuntimeException) {
            e.printStackTrace();
            if(e.getCause() instanceof ServiceThrowable){
                return new RestReturnResult(CommonConstants.FAIL,e.getMessage());
            }else{
                return new RestReturnResult(CommonConstants.FAIL,"系统异常");
            }
        } else {
            return RestReturnResult.error();
        }
    }

//    @InitBinder
//    public void initBinder(WebDataBinder binder, WebRequest request) {
//
//        //转换日期
//        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
//    }
}